<template>
    <div v-if="isLoading" class="loading">
        <div class="loading-spinner">加载中...</div>
    </div>
    <div v-else class="page">
        <div class="el-header-class">
            <el-image src="https://cdn.static.17k.com/cms_static_pic/cms_resource/2025/07/16/1752659187002.jpg"
                      alt=""
                      style="width:1200px"
                      :lazy="true"
            >
            </el-image>
        </div>
        <div class="main-good">
            <div class="left-box">
                <div class="box-header" >
                    <div style="font-size:2.5rem;margin-right: 20px;font-weight: bold">本周主打</div>
                        <el-button
                            v-for="(item, index) in data.text"
                            :key="index"
                            class="el-button-class-a"
                            :class="{ 'active': activeCategory === index }"
                            @mouseenter="handleCategoryChange(index)"
                        >
                            {{ item.title }}
                        </el-button>
    <!--            下划线-->
                </div>
                <divider-x />
                <div class="carousel-box">
                    <!--            轮播图-->
                    <div class="carousel-img">
                        <el-carousel height="400px" style="width: 530px; ">
                            <el-carousel-item v-for="(imgItem, imgIndex) in currentCategoryImgs" :key="imgIndex">
                                <el-image :src="imgItem.coverUrl"
                                          alt="轮播图" style="height: 100%; width: 100%; object-fit: cover;"
                                          @click="goToDetail(imgItem.bookId)"
                                          :lazy="true"
                                ></el-image>
                            </el-carousel-item>
                        </el-carousel>
    <!--                    订阅按钮-->
                        <div class="sub-category">
                            <el-button
                                v-for="(subItem, subIndex) in currentCategorySub"
                                :key="subIndex"
                                class="sub-button"
                                size="large"
                                :class="{ 'sub-active': activeSub === subIndex }"
                                @mouseenter="activeSub = subIndex"
                            >
                                {{ subItem.title }}
                            </el-button>
                        </div>

                        <!-- 周榜列表内容（核心：显示当前选中的周榜数据） -->
                        <div class="ranking-list">
                            <div
                                v-for="(item, i) in limitedRankingList"

                                :key="i"
                                class="ranking-item"
                            >
                                <!-- 排名数字 -->
                                <rank-number :rank="i+1"></rank-number>
                                <!-- 内容文本 -->
                                <span class="rank-text" @click="goToDetail(limitedRankingBook[i])">{{ item }}</span>
                            </div>
                        </div>
                    </div>
    <!--                中间两行小字-->
                    <div class="text-list">
                        <div v-for="item in data.fonts" :key="item" class="text-class-a">
                                <div class="h2-class" @click="goToDetail(item.bookId)">{{item.novelName}}</div>
                                <div class="text-class" @click="goToDetail(item.bookId)">{{item.intro}}</div>
                            <el-divider></el-divider>
                        </div>
                    </div>
                </div>
            </div>
            <div class="right-box">
    <!--            新闻-->
                    <news-card/>
            </div>
        </div>
        <el-divider style="margin: 0;"></el-divider>
        <div class="good-class-b">
    <!--    编辑推荐    -->
            <div class="left-box-class">
                <div class="text-class-b" >编辑推荐</div>
                <divider-x/>
                <div class="text-list-class" >
                    <el-button
                        class="el-button-class-b"
                        v-for="(item, index) in data.recommend"
                        :key="index"
                        :class="{ 'active':  recommendIndex=== index }"
                        @click="recommendIndex = index"
                    >{{item.title}}</el-button>

                </div>
                <div class="text-list-class-main">
                    <div v-for="(category, idx) in recommendData.category"
                         :key="idx"
                         class="text-class-c">
                        <span class="text-class-d">[{{ category }}]</span>
                        <span class="text-class-e" @click="goToDetail(recommendData.bookId[idx])">{{ recommendData.novelName[idx] }}</span>
                    </div>
                </div>
            </div>
    <!--  男生作品点击榜      -->
            <div class="right-box-class">
                <div class="text-class-b" >男生作品点击榜</div>
                <divider-x/>
                <div class="text-list-class">
                    <el-button
                        v-for="(item, index) in data.boy"
                        :key="index"
                        class="el-button-class-c"
                        :class="{ 'active': boyIndex === index }"
                        @click="boyIndex = index"
                    >
                        {{ item.title }}
                    </el-button>
                </div>
                <div class="text-list-class-main">
                    <div
                        v-for="(category, idx) in boyData.category"
                        :key="idx"
                        class="text-class-c"
                    >
                        <div>
                            <div class="box-class-a">
                                <rank-number :rank="idx + 1" />
                                <span class="text-class-g" @click="goToDetail(boyData.bookId[idx])">[{{ category }}]{{ boyData.novelName[idx] }}</span>
                                <span class="text-class-z">{{ boyData.clickCount[idx] }}</span>
                            </div>
                            <div v-show="idx === 0" >
                                <div  class="box-class" @click="goToDetail(boyData.bookId[idx])">
                                    <el-image :src="boyData.coverUrl[idx]" style="width: 160px;height: 200px" :lazy="true">
                                        <template #error>
                                            <el-image
                                                src="https://oss.itbaima.cn/hub/1075/image-20250724qx9izaf1q.jpeg"
                                                style="width: 100%; height: 100%"
                                                :lazy="true"
                                            ></el-image>
                                        </template>
                                    </el-image>
                                    <span class="text-class-h">{{ boyData.intro [idx]}}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div >
    <!--   女生作品电击榜     -->
            <div class="right-box-class">
                <div class="text-class-b" >女生作品点击榜</div>
                <divider-x/>
                <div class="text-list-class" >
                    <el-button
                        class="el-button-class-c"
                        v-for="(item, index) in data.girl"
                        :key="index"
                        :class="{ 'active': girlIndex === index }"
                        @click="girlIndex = index"
                    >{{item.title}}</el-button>

                </div>
                <div class="text-list-class-main">
                    <div v-for="(category, idx) in girlData.category"
                         :key="idx"
                         class="text-class-c">
                        <div>
                            <div class="box-class-a">
                                <rank-number :rank="idx + 1" />
                                <span class="text-class-g" @click="goToDetail(girlData.bookId[idx])">[{{ category }}] {{ girlData.novelName[idx] }}</span>
                                <span class="text-class-z">{{ girlData.clickCount[idx] }}</span>
                            </div>
                            <div v-show="idx === 0" >
                                <div  class="box-class" @click="goToDetail(girlData.bookId[idx])">
                                    <el-image :src="girlData.coverUrl[idx]" style="width: 160px;height: 200px" :lazy="true">
                                        <template #error>
                                            <el-image
                                                src="https://oss.itbaima.cn/hub/1075/image-20250724qx9izaf1q.jpeg"
                                                style="width: 100%; height: 100%"

                                            ></el-image>
                                        </template>
                                    </el-image>
                                    <span class="text-class-h">{{ girlData.intro[idx] }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
    <!--   新人作品点击榜     -->
            <div class="right-box-class-z">
                <div class="text-class-b" >新人作品点击榜</div>
                <divider-x/>
                <div class="text-list-class" >
                    <el-button
                        class="el-button-class-d"
                        v-for="(item, index) in data.newp"
                        :key="index"
                        :class="{ 'active': newpIndex === index }"
                        @click="newpIndex = index"
                    >{{item.title}}</el-button>

                </div>
                <div class="text-list-class-main">
                    <div v-for="(category, idx) in newpData.category"
                         :key="idx"
                         class="text-class-c">
                        <div>
                            <div class="box-class-a" >
                                <rank-number :rank="idx + 1" />
                                <span class="text-class-g" @click="goToDetail(newpData.bookId[idx])">[{{ category }}] {{ newpData.novelName[idx] }}</span>
                                <span class="text-class-z">{{ newpData.clickCount[idx] }}</span>

                            </div>
                            <div v-show="idx === 0" >
                                <div  class="box-class" @click="goToDetail(newpData.bookId[idx])">
                                    <el-image :src="newpData.coverUrl[idx]" style="width: 160px;height: 200px" :lazy="true">
                                        <template #error>
                                            <el-image
                                                src="https://oss.itbaima.cn/hub/1075/image-20250724qx9izaf1q.jpeg"
                                                style="width: 100%; height: 100%"
                                            ></el-image>
                                        </template>
                                    </el-image>
                                    <span class="text-class-h">{{ newpData.intro[idx] }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
import { reactive,computed,ref,onMounted} from 'vue'
import RankNumber from "@/components/rank-number.vue";
import NewsCard from "@/components/news/news-card.vue";
import DividerX from "@/components/divider-x.vue";
import request from '@/utils/request.js';
import {useRouter} from "vue-router";
import {ElLoading} from "element-plus";
// 数据加载状态（true：加载中，false：加载完成）
const isLoading = ref(true);
// 获取路由实例
const router = useRouter();
// 跳转至详情页的方法
// 挂载时加载数据
onMounted(() => {
    // 1. 优先加载首屏核心数据（本周主打 + 头部推荐）
    loadCriticalData();
    // 2. 延后加载次要数据（利用浏览器空闲时间）
    requestIdleCallback(() => {
        loadSecondaryData();
    }, { timeout: 1000 }); // 3秒内未空闲则强制加载
});
const data = reactive({
    recommend:[{title: "", category:[], novelName: [],bookId:[]}],
    boy:[{title: "", category:[], novelName: [], coverUrl:"", intro:"" ,clickCount:"",bookId:[]}],
    girl:[{title: "", category:[], novelName: [], coverUrl:"", intro:"",clickCount:"",bookId:[]}],
    newp:[{title: "", category:[], novelName: [], coverUrl:"", intro:"",clickCount:"",bookId:[]}],
    text: [{title: "", imgs: [{intro: "", coverUrl: '',bookId:[]},], sub:[{title: "", novelName: [],bookId:[]}]},],
    fonts: [{intro:"",novelName:[],bookId:[]}]
})

const goToDetail = (id) => {
    router.push({
        name: 'bookList', // 对应路由配置中的name
        params: { id } // 传递id参数
    });
};
const loadCriticalData=() => {
    const loading = ElLoading.service({
        // lock: true,
        // text: '加载中...',
        // background: 'rgba(0, 0, 0, 0)'
        target: '.main-good'
    });
    //榜单数据
    request.get('/api/books/rank').then(res => {
        if (res.code === 200) {
            data.text = res.data
            console.log(res.data)
        }
        else {
            data.text = []
        }
    })

// 获取新书频道
    request.get('/api/books/channel/new').then(res => {
        if (res. code === 200) {
            data.newp = res.data
            console.log(res.data)
        }
        else {
            data.girl = []
        }
    })
    //两行字
    request.get('/api/books/nameandintro').then(res => {
        if (res.code === 200) {
            data.fonts = res.data
            console.log(res.data)
        }
        else {
            data.fonts = []
        }
    }).finally(()=>{
        isLoading.value = false;
        loading.close();})
}

const loadSecondaryData=() => {
    // 获取推荐频道
    request.get('/api/books/recommend-all').then(res => {
        if (res.code === 200) {
            data.recommend = res.data
            console.log(res.data)
        }
        else {
            data.recommend = []
        }
    })
// 获取男生频道
    request.get('/api/books/channel/boy').then(res => {
        if (res.code === 200) {
            data.boy = res.data
            console.log(res.data)
        }
        else {
            data.boy = []
        }
    })
// 获取女生频道
    request.get('/api/books/channel/girl').then(res => {
        if (res.code === 200) {
            data.girl = res.data
            console.log(res.data)
        }
        else {
            data.girl = []
        }
    })
}
// 一级分类索引（全站/男生等）
const activeCategory = ref(0)
// 二级分类索引（周榜类型）
const activeSub = ref(0)
// 切换一级分类时，重置二级分类索引
const handleCategoryChange = (index) => {
    activeCategory.value = index
    activeSub.value = 0 // 重置为第一个周榜
}
// 获取当前一级分类的图片
const currentCategoryImgs = computed(() => {
    return data.text[activeCategory.value].imgs
})
// 获取当前一级分类的子分类（周榜）
const currentCategorySub = computed(() => {
    return data.text[activeCategory.value].sub
})
// 获取当前选中的周榜列表数据（核心）
const currentRankingList = computed(() => {
    const subList = data.text[activeCategory.value].sub
    return subList[activeSub.value]?.novelName || []
})
// 获取当前选中的周榜列表数据（核心）
const currentRankingBook = computed(() => {
    const subList = data.text[activeCategory.value].sub
    return subList[activeSub.value]?.bookId || []
})
const limitedRankingList = computed(() => {
    return currentRankingList.value.slice(0, 15)  // 只取前15项
})
const limitedRankingBook = computed(() => {
    return currentRankingBook.value.slice(0, 15)  // 只取前15项
})
// 各列表独立索引
const recommendIndex = ref(0)
const boyIndex = ref(0)
const girlIndex = ref(0)
const newpIndex = ref(0)

// 各列表数据计算
const recommendData = computed(() => data.recommend[recommendIndex.value])
const boyData = computed(() => data.boy[boyIndex.value])
const girlData = computed(() => data.girl[girlIndex.value])
const newpData = computed(() => data.newp[newpIndex.value])
</script>
<style scoped>
.loading {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
}

.loading-spinner {
    font-size: 1rem;
    color: #409eff;
    font-weight: bold;
}
.page{
    width: 100%;
    height: 100%;
}
.el-header-class{
    width: 1200px;
    height: 100px;
    margin: 20px auto;
    border-radius: 20px;
}
.main-good{
    margin-top: 30px;
    width: 1200px;
    height: 100%;
    display: flex;
/*    左右分开*/
}
.left-box{
    width: 900px;
}
.right-box{
        width: 300px;
    margin-left: 40px;
}

.el-button-class-a{
    margin: 10px 0 0 0;
    border-radius: 0 ;
    border-left: none ;
    color: #000000;
    background-color: white;
}
.el-button-class-a:hover{
    background-color: #409eff;
    color: white;
}
.el-button-class-a.active{
    background-color: #409eff;
    color: white;
}
.box-header{
    display: flex;
}
.carousel-box{
    display: flex;
    gap: 20px;
    align-items: flex-start;
    /*padding: 20px; */
}
/*.carousel-img{*/
/*    flex: 2;*/
/*}*/
/*.text-list{*/
/*    flex: 1;*/
/*}*/

/* 原有样式保持不变，新增以下样式 */

/* 二级分类（周榜）按钮样式 */
.sub-category {
    display: flex;
    margin: 15px 0;
    gap: 5px;
}

.sub-button {
    border-radius: 4px ;
    /*padding: 5px 10px ;*/
    font-size: 1rem ;
    margin: 0;
    border: 1px solid #ccc;
    cursor: pointer;
    background-color: white;
    color: #333;
    transition: background-color 0.3s ease;
    padding: 16px 30px;
}

.sub-button.sub-active {
    background-color: #409eff;
    color: white;
    border-color: #409eff ;
}

/* 周榜列表样式 */
.ranking-list {
    display: grid;
    /*每行5个项目，自动换行 */
    grid-template-rows: repeat(5, auto);
    /*自动计算列数（最多3列）*/
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    /*/ 关键：竖向排列（先列后行） */
    grid-auto-flow: column;
    /*padding: 10px;*/
}
/* 单个排名项 */
.ranking-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-size: 1rem;
}

.rank-text {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 90px;  /* 调整此值控制显示字数 */
}
.rank-text:hover{
    color: #409eff;
    cursor: pointer;
    text-decoration: underline;
    transition: all 0.3s ease;
    transform: scale(1.05);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    background-color: #f5f5f5;
    max-width: 400px;
}
/*==============*/




.text-class-a{
    width: 100%; /* 确保每个块宽度一致 */
    padding-bottom:10px ;
    display: flex;
    flex-direction: column;
}
.h2-class{
    font-size: 1.3rem;
    font-weight: bold;
}
.h2-class:hover{
    color: #409eff;
    cursor: pointer;
    text-decoration: underline;
    transition: all 0.3s ease;
    transform: scale(1.05);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    background-color: #f5f5f5;
    max-width: 330px;

}
.text-class {
    font-size: 0.75rem;
    font-weight: bold;
    color: #999999;
    /* 默认最多显示3行 */
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    overflow: hidden;
    /* 增加过渡效果，使hover状态变化更平滑 */
    transition: all 0.3s ease;
    /*padding: 5px; !* 预留内边距，避免hover时内容突然收缩 *!*/
}
.text-class:hover{
    color: #409eff;
    cursor: pointer;
    text-decoration: underline;
    transform: scale(1.05);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    background-color: #f5f5f5;
    max-width: 330px; /* 保持最大宽度限制 */
    /* 核心：取消行数限制，显示全部文本 */
    -webkit-line-clamp: unset; /* 移除行数限制 */
    display: block; /* 恢复默认块级显示方式，取消-webkit-box限制 */
    overflow: visible; /* 允许内容溢出容器（配合max-width控制） */
    white-space: normal; /* 允许自动换行 */
    z-index: 10; /* 确保hover时文本在其他元素上方 */
    position: relative; /* 配合z-index生效 */
}
/*下面的推荐列表*/
.good-class-b{
    margin-top: 10px;
    width: 1200px;
    height: 100%;
    display: flex;
    margin-bottom: 1000px;
}
.left-box-class{
    width: 200px;
    margin-right: 40px;
}
.right-box-class{
    width: 325px;
    margin-left: 30px;
}
.right-box-class-z{
    width: 345px;
    margin-left: 30px;

}
.text-class-b{
    font-size: 2.3rem;
    font-weight: bold;
 }
.text-list-class{
    display: flex;
    margin-bottom: 20px;
    /* 允许换行 */
    flex-wrap: wrap;
    /* 按钮之间的间距 */
    gap: 0;

}
.el-button-class-b{
    width: 60px;
    /*margin-left: 10px;*/
}
.el-button-class-c{
    width: 20px;
    /*margin-left: 10px;*/
    /*margin-top: 2px;*/
    margin: 5px;

}
.el-button-class-d{
    width: 10px;
    /*margin-left: 10px;*/
    margin: 3px;
}
.el-button-class-b:hover{
    background-color: #409eff;
    color: white;
}
.text-list-class .active {
    background-color: #409eff;
    color: white;
}
.text-list-class-main{
    display: flex;
    flex-direction: column;
}
.text-class-c{
    display: flex;

}
.text-class-d{
    font-size: 1rem;
    font-weight: bold;
    color: #797979;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 90px;
    margin:3px;
}

.text-class-e{
    font-size: 1rem;
    font-weight: bold;
    color: #737373;
    white-space: nowrap;
    overflow: hidden;
    margin-left: 10px;
    text-overflow: ellipsis;
    max-width: 90px;
}
.text-class-e:hover{
    color: #409eff;
    cursor: pointer;
    text-decoration: underline;
    transition: all 0.3s ease;
    transform: scale(1.05);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    background-color: #f5f5f5;
    max-width: 330px;

}
.box-class-a {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%; /* 确保容器占满宽度 */
    white-space: nowrap; /* 防止换行 */
    margin-bottom: 2px; /* 增加间距，使布局更清晰 */
}


.text-class-g{
    font-size: 1rem;
    font-weight: bold;
    color: #797979;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 190px;
}
.text-class-g:hover {
    color: #409eff;
    cursor: pointer;
    text-decoration: underline;
    transition: all 0.3s ease;
    transform: scale(1.05);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    background-color: #f5f5f5;
    max-width: 260px;
}

.text-class-z {
    font-size: 1rem;
    color: #797979;
    /* 移除 margin-left: 100px; */
    margin-left: 10px; /* 仅保留与书名的小间距 */
}

.box-class{
    padding: 10px;
    display: flex;
    margin: 20px 0 20px 0;
    background-color: #d2d2d2;

}
.text-class-h {
    font-size: 0.9rem;
    font-weight: normal; /* 细体 */
    color: #797979;
    margin-left: 5px;
    max-width: 90px;

    /* 关键属性：控制多行文本截断 */
    display: -webkit-box; /* 将元素作为弹性伸缩盒子模型显示 */
    -webkit-box-orient: vertical; /* 设置伸缩盒子的子元素排列方式为垂直 */
    -webkit-line-clamp: 5; /* 最多显示5行 */
    overflow: hidden; /* 超出部分隐藏 */
    text-overflow: ellipsis; /* 超出部分用省略号表示 */
    white-space: normal; /* 恢复默认换行（与单行截断的nowrap相反） */
}
</style>